package com.tanhua.server.service;

import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.autoconfig.template.SmsTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.dubbo.api.UserApi;
import com.tanhua.model.domain.User;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserService {

    @Autowired
    private SmsTemplate template;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @DubboReference
    private UserApi userApi;

    public void sendMsg(String phone) {
        //String code = RandomStringUtils.randomNumeric(6);
        String code ="123456";
        //template.sendSms(phone,code);
        redisTemplate.opsForValue().set("CHECK_CODE_"+phone,code, Duration.ofMinutes(5));
    }

    public Map loginVerification(String phone, String code) {
        String redisCode = redisTemplate.opsForValue().get("CHECK_CODE_" + phone);

        if (StringUtils.isEmpty(redisCode)||(!redisCode.equals(code))){
            throw new RuntimeException("验证码错误");
        }
        redisTemplate.delete("CHECK_CODE_"+phone);

        User user = userApi.findByMobile(phone);

        boolean isNew=false;
        if (user==null){
            user=new User();
            user.setMobile(phone);
            user.setCreated(new Date());
            user.setUpdated(new Date());
            user.setPassword(DigestUtils.md5Hex("123456"));
            Long userId=userApi.save(user);
            user.setId(userId);
            isNew=true;

//            注册环信用户
            String hxUser ="hx"+user.getId();
            Boolean create = huanXinTemplate.createUser(hxUser, Constants.INIT_PASSWORD);
            if (create){
                user.setHxUser(hxUser);
                user.setHxPassword(Constants.INIT_PASSWORD);
                userApi.update(user);
            }
        }

        Map tokenMap = new HashMap();
        tokenMap.put("id",user.getId());
        tokenMap.put("mobile",phone);
        String token= JwtUtils.getToken(tokenMap);

        Map retMap=new HashMap();
        retMap.put("token",token);
        retMap.put("isNew",isNew);


        return retMap;
    }
}
